<?php
/**
 * Application bootstrap class
 *
 * Resources initialization methods are currently in this class
 * but if specific resource initialization / code grows, it should
 * be moved to a separate resource class
 *
 * @author B. Krastev
 * @version 0.1.2
 *
 */
class Icygen_Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    protected function _initUmask()
    {
        umask(002);
    }

    /**
     * Register default module with its namespace
     *
     */
    protected function _initAutoloader()
    {
        return new Zend_Application_Module_Autoloader(array(
            'namespace' => 'Default',
            'basePath'  => APPLICATION_PATH . '/modules/default',
        ));
    }

    /**
     * Get rid of the annoying message "It is not safe to rely on systems timezone..."
     *
     */
    public function _initTimeZone()
    {
        date_default_timezone_set('Europe/Sofia');

        /**
         * Set Zend_Date to use PHP formatting
         */
      //  Zend_Date::setOptions(array('format_type' => 'php'));
    }

    /**
     * Register Icygen_Exception as error handler
     *
     * @return Zend_Log
     */
    public function _initErrorHandler()
    {
        Icygen_Exception::registerErrorHandler();

        /**
         * @todo Make path configurable in application.xml
         */
        try {
            $errorLog = new Zend_Log(new Icygen_Log_Writer_FileRotate(APPLICATION_PATH . '/log/error.log'));
            Icygen_Exception::setLog($errorLog);

        } catch (Exception $e) {
            $errorLog = null;
        }

        return $errorLog;
    }

    public function _initDispatcher()
    {
        /**
         * Ensure FrontController is bootstrapped
         */
        $this->bootstrap('FrontController');

        $front = $this->getResource('frontController');

        $dispatcher = new Icygen_Controller_Dispatcher_Standard();

        $dispatcher->setControllerDirectory($front->getDispatcher()->getControllerDirectory());

        $front->setDispatcher($dispatcher);

        return $dispatcher;
    }

    /**
     * Initialize Zend_Layout
     *
     * @return Zend_Layout
     */
    public function _initLayout()
    {
        /**
         * Check if view is initialized
         */
        if (!$this->hasResource('View')) {
            $this->registerPluginResource('View');
            $this->bootstrapView();
        }

        $view = $this->getResource('View');

        $options = $this->getOption('resources');

        /**
         * Merge layout config options with view instance
         * so action views and layout views are the same object and share assigned variables
         */
        $layoutOptions = array('view' => $view);
        if ($options && is_array($options) && isset($options['layout'])
            && is_array($options['layout'])) {

            $layoutOptions = array_merge($layoutOptions, $options['layout']);

            if (isset($layoutOptions['doctype'])) {
                $view->doctype()->setDoctype($layoutOptions['doctype']);
            }
        }

        /**
         * Set content type and charset
         *
         * @todo Migrate to application/xhtml+xml one beautiful day ;)
         */
        $view->headMeta()->prependHttpEquiv('Content-Type',
                                            'text/html; charset=' . $view->getEncoding());

        $layout = Zend_Layout::startMvc($layoutOptions);

        $this->getResource('FrontController')->registerPlugin(new Icygen_Controller_Plugin_LayoutActionStack(), 96);

        return $layout;
    }

    /**
     * Init session namespace for current project
     *
     * @return Zend_Session_Namespace
     */
    public function _initSession()
    {
        $options = $this->getOption('resources');

        if (!$options || !isset($options['session']['namespace'])) {
            $namespace = 'Icygen';
        } else {
            $namespace = $options['session']['namespace'];
        }

        /**
         * Ensure FrontController is bootstrapped
         */
        $this->bootstrap('FrontController');

        $front  = $this->getResource('frontController');
        $member = Zend_Auth_Storage_Session::MEMBER_DEFAULT;
		
		if (preg_match('/admin/', $_SERVER['REQUEST_URI'])) {
			$member = 'admin';
		}
		
        /*$parts  = explode('/', str_replace(rtrim($front->getBaseurl(), '/') . '/', '', $_SERVER['REQUEST_URI']));

        if ($parts[0] && isset($options['session'][$parts[0]])) {
        	$member = $parts[0];
        }*/

        $session = new Zend_Session_Namespace($namespace);

        Zend_Auth::getInstance()->setStorage(new Icygen_Auth_Storage_Session($namespace . 'Auth', $member));

        if (Zend_Auth::getInstance()->hasIdentity() && $session->rememberMe) {
            Zend_Session::rememberMe(365*24*3600);
        }

        return $session;
    }

    /**
     * Init soap options
     *
     * @return array
     */
    public function _initSoap()
    {
        $soapConfig = $this->getOption('soap');

        Zend_Registry::set('SoapConfig', $soapConfig);

        return $soapConfig;
    }

    /**
     * Init global settings
     *
     * @return array
     */
    public function _initGlobalSettings()
    {
        $settings = null;

        $file = APPLICATION_PATH . '/configs/settings.xml';

        if (file_exists($file)) {
            $settings = new Zend_Config_Xml($file);
        }

        Zend_Registry::set('Global_Settings', $settings);

        return $settings;
    }
}

